from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework import mixins
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import SKU
from goods.serializers import SKUSerializer, SKUIndexSerializer


# GET /categories/(?P<category_id>\d+)/skus/
# 根据第三级分类ID获取分类SKU商品的数据
class SKUlistView(ListAPIView):
    # 排序
    filter_backends = [OrderingFilter]
    # 指定排序字段
    ordering_fields = ('create_time','price','sales')

    serializer_class = SKUSerializer

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id)
    # def get(self,request,category_id):
    #     """根据第三级分类ID获取分类SKU商品的数据:"""
    #     # 1 根据id查询数据库中的所有的该三级分类商品
    #     skus = self.get_queryset()
    #     # 2 序列化并返回给前端
    #     serializer = self.get_serializer(skus,many=True)
    #     return Response(serializer.data)

# GET /skus/search/?text=<搜索关键字>
# 商品搜索关键字接口
class SKUSearchViewSet(HaystackViewSet):
    # 指定索引类对应的模型类
    index_models = [SKU]

    # 指定搜索结果序列化时所使用的序列化器类
    # 搜索结果中每个对象都包含两个属性：
    # text: 索引字段的内容
    # object: 从数据库中搜索出模型对象（此处是SKU模型对象)
    serializer_class = SKUIndexSerializer
